package service

import (
	"context"
	pb "doctor-srv/basic/proto"
	"doctor-srv/basic/config"
	"doctor-srv/handler/model"
)

type MedicineService struct {
	pb.UnimplementedMedicineServer
}

// GetMedicineList 获取药品列表
func (s *MedicineService) GetMedicineList(ctx context.Context, req *pb.GetMedicineListReq) (*pb.GetMedicineListResp, error) {
	medicines, total, err := model.GetMedicineList(config.DB, int(req.Page), int(req.PageSize), req.Keyword, req.Category)
	if err != nil {
		return nil, err
	}

	var medicineInfos []*pb.MedicineInfo
	for _, medicine := range medicines {
		medicineInfos = append(medicineInfos, &pb.MedicineInfo{
			MedicineId:       int64(medicine.ID),
			Name:             medicine.Name,
			Category:         medicine.Category,
			Efficacy:         medicine.Efficacy,
			Contraindication: medicine.Contraindication,
			SideEffect:       medicine.SideEffect,
			Price:            medicine.Price,
			ImageUrl:         medicine.ImageUrl,
		})
	}

	return &pb.GetMedicineListResp{
		Medicines: medicineInfos,
		Total:     total,
	}, nil
}

// GetMedicineDetail 获取药品详情
func (s *MedicineService) GetMedicineDetail(ctx context.Context, req *pb.GetMedicineDetailReq) (*pb.GetMedicineDetailResp, error) {
	var medicine model.Medicine
	err := medicine.GetMedicineByID(config.DB, req.MedicineId)
	if err != nil {
		return nil, err
	}

	return &pb.GetMedicineDetailResp{
		Medicine: &pb.MedicineInfo{
			MedicineId:       int64(medicine.ID),
			Name:             medicine.Name,
			Category:         medicine.Category,
			Efficacy:         medicine.Efficacy,
			Contraindication: medicine.Contraindication,
			SideEffect:       medicine.SideEffect,
			Price:            medicine.Price,
			ImageUrl:         medicine.ImageUrl,
		},
	}, nil
}

// CreatePrescription 创建处方
func (s *MedicineService) CreatePrescription(ctx context.Context, req *pb.CreatePrescriptionReq) (*pb.CreatePrescriptionResp, error) {
	// 开启事务
	tx := config.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 创建处方
	prescription := model.Prescription{
		PrescriptionNo: GenerateOrderNo("PRE"),
		ConsultationID: req.ConsultationId,
		DoctorID:       req.DoctorId,
		PatientID:      req.PatientId,
		AuditStatus:    0, // 待审核
	}

	if err := prescription.CreatePrescription(tx); err != nil {
		tx.Rollback()
		return nil, err
	}

	// 创建处方明细
	var totalAmount float64
	for _, item := range req.Items {
		var medicine model.Medicine
		if err := medicine.GetMedicineByID(tx, item.MedicineId); err != nil {
			tx.Rollback()
			return nil, err
		}

		prescriptionItem := model.PrescriptionItem{
			PrescriptionID: int64(prescription.ID),
			MedicineID:     item.MedicineId,
			MedicineName:   item.MedicineName,
			Quantity:       int(item.Quantity),
			Dosage:         item.Dosage,
			Price:          medicine.Price,
		}

		if err := tx.Create(&prescriptionItem).Error; err != nil {
			tx.Rollback()
			return nil, err
		}

		totalAmount += medicine.Price * float64(item.Quantity)
	}

	// 更新处方总金额
	prescription.TotalAmount = totalAmount
	if err := tx.Save(&prescription).Error; err != nil {
		tx.Rollback()
		return nil, err
	}

	tx.Commit()

	return &pb.CreatePrescriptionResp{
		PrescriptionId: int64(prescription.ID),
		PrescriptionNo: prescription.PrescriptionNo,
	}, nil
}

// GetPrescriptionStatus 获取处方状态
func (s *MedicineService) GetPrescriptionStatus(ctx context.Context, req *pb.GetPrescriptionStatusReq) (*pb.GetPrescriptionStatusResp, error) {
	var prescription model.Prescription
	err := prescription.GetPrescriptionByID(config.DB, req.PrescriptionId)
	if err != nil {
		return nil, err
	}

	return &pb.GetPrescriptionStatusResp{
		AuditStatus: int32(prescription.AuditStatus),
		AuditReason: prescription.AuditReason,
	}, nil
}

// CreateMedicineOrder 创建药品订单
func (s *MedicineService) CreateMedicineOrder(ctx context.Context, req *pb.CreateMedicineOrderReq) (*pb.CreateMedicineOrderResp, error) {
	// 获取处方信息
	var prescription model.Prescription
	err := prescription.GetPrescriptionByID(config.DB, req.PrescriptionId)
	if err != nil {
		return nil, err
	}

	// 检查处方是否已审核通过
	if prescription.AuditStatus != 1 {
		return &pb.CreateMedicineOrderResp{
			OrderId: 0,
			OrderNo: "",
		}, nil
	}

	// 创建订单
	order := model.MedicineOrder{
		OrderNo:         GenerateOrderNo("MED"),
		PrescriptionID:  req.PrescriptionId,
		PatientID:       req.PatientId,
		TotalPrice:      prescription.TotalAmount,
		DeliveryAddress: req.DeliveryAddress,
		Status:          1, // 已下单
	}

	if err := order.CreateMedicineOrder(config.DB); err != nil {
		return nil, err
	}

	return &pb.CreateMedicineOrderResp{
		OrderId: int64(order.ID),
		OrderNo: order.OrderNo,
	}, nil
}

// GetMedicineOrderList 获取药品订单列表
func (s *MedicineService) GetMedicineOrderList(ctx context.Context, req *pb.GetMedicineOrderListReq) (*pb.GetMedicineOrderListResp, error) {
	orders, total, err := model.GetMedicineOrderList(config.DB, req.PatientId, int(req.Page), int(req.PageSize))
	if err != nil {
		return nil, err
	}

	var orderInfos []*pb.MedicineOrderInfo
	for _, order := range orders {
		orderInfos = append(orderInfos, &pb.MedicineOrderInfo{
			OrderId:    int64(order.ID),
			OrderNo:    order.OrderNo,
			Status:     int32(order.Status),
			TotalPrice: order.TotalPrice,
			CreatedAt:  order.CreatedAt.Unix(),
		})
	}

	return &pb.GetMedicineOrderListResp{
		Orders: orderInfos,
		Total:  total,
	}, nil
}

